﻿using Haidou.Wpf.Util.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;

namespace Haidou.Wpf.Util
{
	/// <summary>
	/// 互斥列表
	/// </summary>
	public static class MutexList
	{
		private static Dictionary<string, Mutex> All { get; set; } = new();

		/// <summary>
		/// 正在使用中
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public static bool IsInUse(string key)
		{
			GC.Collect();

			return Mutex.TryOpenExisting(@"Global\MjAi.Ui" + key.Remove("\\"), out Mutex? mutex);
		}

		public static void Add(string key)
		{
			if (All.ContainsKey(key))
			{
				Remove(key);
			}

			Mutex mutex = new(false, @"Global\MjAi.Ui" + key.Remove("\\"), out _);

			MutexSecurity sec = new();
			sec.AddAccessRule(new MutexAccessRule(Environment.UserDomainName + "\\" + Environment.UserName, MutexRights.FullControl, AccessControlType.Allow));

			mutex.SetAccessControl(sec);

			All.Add(key, mutex);
		}

		public static bool Exists(string key)
		{
			return All.Any(f => f.Key == key);
		}

		public static void Remove(string key)
		{
			Mutex current = All.FirstOrDefault(f => f.Key == key).Value;

			if (current == null)
			{
				return;
			}

			current.Dispose();

			All.Remove(key);

			GC.Collect();

			//var c = IsInUse(key);
		}

		public static void RemoveAll()
		{
			foreach (KeyValuePair<string, Mutex> mutex in All)
			{
				mutex.Value.Dispose();
			}

			All.Clear();
			GC.Collect();
		}
	}
}
